# 导入模块
import sys 
from PyQt5.QtWidgets import*
from PyQt5.QtCore import*
from PyQt5.QtGui import*
from ui.Ui_chess import Ui_Form

class MainWindow(QWidget):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.ui=Ui_Form()
        self.ui.setupUi(self)
        self.init_ui()
        
    def init_ui(self):
        #设置默认值-1
        self.x = -1
        self.y = -1
        self.gridWidth=-1
        self.gridHeight=-1
        #鼠标点击的下标
        self.press_i=-1
        self.press_j=-1
        #设置窗口最小大小
        self.setMinimumSize(QSize(800,700))
        
        
    
    #绘图事件
    def paintEvent(self,event:QPaintEvent):
        #打印绘图区域
        # print(event.rect())
        #定义画家对象
        painter=QPainter(self)
        #画背景图
        painter.drawPixmap(0, 0, self.width(), self.height(),QPixmap("./img/img.png"))
        #窗口分12份 //求商不要小数
        self.gridWidth=self.width()//12
        self.gridHeight=self.height()//12
        #确定起点
        self.x=self.gridWidth*2
        self.y=self.gridHeight*2
        
        #定义一个画笔对象 ，设置颜色线宽
        pen=QPen(Qt.black,2)
        
        #画笔交给画家
        painter.setPen(pen)
        
        #画横线
        for i in range(9):
            painter.drawLine(self.x,self.y+i*self.gridHeight,self.x+self.gridWidth*8,self.y+i*self.gridHeight)
            painter.drawLine(self.x+i*self.gridWidth,self.y,self.x+i*self.gridWidth,self.y+self.gridHeight*8)
        
        #定义一个画笔对象 ，设置颜色线宽
        pen=QPen(Qt.green,2,Qt.SolidLine)
        
        #画笔交给画家
        painter.setPen(pen)
        #鼠标坐标不为-1 画棋子
        if self.press_i!=-1 :
            painter.drawPixmap(QRect(self.x+self.press_i*self.gridWidth,
                                    self.y+self.press_j*self.gridHeight,
                                    self.gridWidth,self.gridHeight),
                                    QPixmap("./img/black.png"))
        #画绿色框
            painter.drawRect(self.x+self.press_i*self.gridWidth,
                                self.y+self.press_j*self.gridHeight,
                                self.gridWidth,self.gridHeight)
    def mousePressEvent(self,event:QMouseEvent):
        #获取鼠标点击的位置
        ex=event.x()
        ey=event.y()
        
        self.press_i=(ex-self.x)//self.gridWidth
        self.press_j=(ey-self.y)//self.gridHeight
        
        #坐标控制在0-7之间
        if self.press_i>=0 and self.press_i<=7 and self.press_j>=0 and self.press_j<=7:
            #刷新绘图区域
            self.update()
            print("点击坐标为：",self.press_i,self.press_j)
        else:
            self.press_i=-1
            self.press_j=-1
        
        

if __name__ == '__main__':
    # 创建应用程序
    app=QApplication(sys.argv)  

    # 创建窗口  不是QWidget, 是自定义的
    window=MainWindow()

    # 显示窗口
    window.show()

    # 等待窗口停止
    sys.exit(app.exec_())  